既然我們使用spring boot方式
那我們就來建立一自定義的@Bean吧

這邊有一篇文章介紹一些常用的@Bean
圖中每一個都是@Bean

參考網址:https://dev.to/pmgysel/learn-spring-boot-by-annotations-1h0i

我比較常使用到的是SimpleDateFormat 很多時候會看到sdf也是同樣的意思 日期時間轉換

這次看到有針對金額轉換的,特別和大家介紹一下

NumberFormatExample 建立一個類別

@Service
public class NumberFormatExample {

    public void numberExampleTest(){
        NumberFormat fmt = NumberFormat.getCompactNumberInstance(Locale.US, NumberFormat.Style.SHORT);
        System.out.println(fmt.format(42_000));          //prints: 42K
        System.out.println(fmt.format(42_000_000));      //prints: 42M
        NumberFormat fmtP = NumberFormat.getPercentInstance();
        System.out.println(fmtP.format(0.42));          //prints: 42%
    }
}

這個@Service 就是說明現在這個類別是一個@Bean

其他撰寫其實和一般寫方法的時候是一樣的~
是不是很簡單。

剛剛建立的@Bean 當服務啟動
表示這個@Bean 被放入 IOC容器中
再來如何放到我們商業邏輯進入點呢?

使用
@Autowired 注入

@Autowired
NumberFormatExample numberFormatExample;

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @EventListener(ApplicationReadyEvent.class)
    public void applicationReady(ApplicationReadyEvent event){
        numberFormatExample.numberExampleTest();
    }

執行結果:
42K
42M
42%

那我們試著把Locale.US 轉為 Locale.TAIWAN
執行結果:
4萬
4200萬
42%

這就是完整的第1個程式囉

補充:

這不是一個給新手的一個教學過程,也寫的不是很完整
希望大家多多包涵囉~

主要是給自己的一個紀錄,也分享給有需要的夥伴
註解部分有提及一些參考的連結,有興趣可以點進去看看喔

這是一個心血來潮,產生的文章
若有喜歡或交流的部分都歡迎在下方留言,多多關照。

#java 17 #spring boot







你可能感興趣的文章

閉包

閉包

What is Azure Release Pipeline

What is Azure Release Pipeline

How to build CICD with Jenkins as code based on container

How to build CICD with Jenkins as code based on container






留言討論